#include <QtGui>

#include "scene.h"
#include "square.h"
#include "circle.h"

Scene::Scene()
{
    setSceneRect(QRectF(0, 0, SCENE_WIDTH, SCENE_HEIGHT));
    elementType = SquareType;
    moveType = NoMove;
}

void Scene::deleteItem()
{
    foreach (QGraphicsItem *item, selectedItems())
    {
        if (item->type() == QGraphicsEllipseItem::Type)
        {
            Element *element = (Element*) item->parentItem();
            element->removeNode((QGraphicsEllipseItem*) item);
        }

        removeItem(item);
    }
}

void Scene::pickSquare()
{
    elementType = SquareType;
}

void Scene::pickCircle()
{
    elementType = CircleType;
}

void Scene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{    
    if (mouseEvent->button() == Qt::RightButton)
    {
        QPointF pos = mouseEvent->scenePos();
        createElement(pos.x(), pos.y());
    }
    else
    {
        QGraphicsScene::mousePressEvent(mouseEvent);
    }
}

Element* Scene::createElement(qreal x, qreal y)
{
    Element* element;
    switch (elementType)
    {
    case SquareType:
        element = new Square();
        addElement(element, x, y);
        break;
    case CircleType:
        element = new Circle();
        addElement(element, x, y);
        break;
    case NodeType:
        // Każdemu zaznaczonemu elementowi dodaj node.
        foreach (QGraphicsItem *item, selectedItems())
        {
            Element *element = (Element*) item;
            if (element->type() == QGraphicsEllipseItem::Type)
            {
                continue;
            }
            element->addNode(x, y);
        }
    }

    if (moveType == CircleMove)
    {
        emit circleMoveInsert(element);
    }

    return element;
}

void Scene::addElement(Element *element, qreal x, qreal y)
{
    addItem(element);
    element->setPos(x, y);
    element->setFlag(QGraphicsItem::ItemIsMovable, true);
    element->setFlag(QGraphicsItem::ItemIsSelectable, true);
    element->setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
    element->setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true);
    element->setSelected(true);
    element->moveType = moveType;
    connect(element, SIGNAL(selectedChange(Element*)), this, SIGNAL(itemSelected(Element*)));
}
